package com.itheima.reggie.controller;

import com.itheima.reggie.commons.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;

import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.itheima.reggie.utils.SMSUtils.sendMessage;

/**
 *
 */
@Api(tags = "手机端")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sendMsg")
    @ApiOperation("发送短信")
    public R<String> sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        System.out.println("phone = " + phone);
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //SMSUtils.sendMessage("黑马旅游", "SMS_195723031", phone, code);
//        session.setAttribute("code",code);
//        session.setAttribute("phone",phone);
        stringRedisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
        log.info(code);
      return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public R<String> login(@RequestBody Map<String,String> param) {
        //1. 获取用户提交参数
        String phone = param.get("phone");
        String code = param.get("code");
        //2. 从会话域中得到验证码
        //String sessionCode = (String) session.getAttribute("code");
        String gencode = stringRedisTemplate.opsForValue().get(phone);

        if (gencode.isEmpty()) {
            return R.error("验证码已过期");
        }
        //3. 如果验证码错误就返回错误信息
        if (!code.equalsIgnoreCase(gencode)) {
            return R.error("验证码错误");
        }

        //4. 验证码正确则调用业务层登录或注册
        User user = userService.login(phone);

        //5. 如果用户不为空，则登录或注册成功
        if (user != null) {
            //登录成功将用户id保存在会话域中
            session.setAttribute("LOGIN_ID", user.getId());
            stringRedisTemplate.delete(gencode);
            return R.success("登录成功");
        }
        //6.否则登录失败
        else {
            return R.error("登录失败");
        }
    }
    @PostMapping("loginout")
    @ApiOperation("退出")
    public R<String> exit(){
        session.invalidate();
        log.info("退出登录");
        return R.success("退出成功");
    }
}
